<?php

namespace App\Logic\Admin;

use App\Constants\ErrorCode;

class RolesLogic
{
    /**
     * Notes:获取角色列表
     * 2025/7/15
     * @return array
     */
    public function list(): array
    {
        $roles = \App\Model\Role::query()->with('menus')->get();
        foreach ($roles as $role) {
            $role->permissions;
        }
        return $roles->toArray();
    }

    /**
     * Note:获取角色详情
     * User: Kong
     * Date: 2025/9/25
     * Time: 12:31
     * @param $data
     * @return array
     * @throws \Exception
     */
    public function detail($data): array
    {
        $id = $data['id']??0;
        if ($id<=0) {
            throw new \Exception('请选择要操作的角色');
        }
        $role = \App\Model\Role::query()->find($id);
        if (! $role) {
            throw new \Exception('未找到数据');
        }
        return $role;
    }

    /**
     * Note:创建角色
     * User: Kong
     * Date: 2025/9/25
     * Time: 14:15
     * @param $data
     * @return mixed
     * @throws \Throwable
     */
    public function create($data)
    {
        $role = \App\Service\Admin\RoleService::createRole($data);
        return $role;
    }

    /**
     * Note:修改角色
     * User: Kong
     * Date: 2025/9/25
     * Time: 14:22
     * @param $data
     * @return mixed
     * @throws \Throwable
     */
    public function update($data)
    {
        $role = \App\Service\Admin\RoleService::updateRole($data);
        return $role;
    }

    /**
     * Note:删除角色
     * User: Kong
     * Date: 2025/9/25
     * Time: 14:22
     * @param $data
     * @return bool|int|mixed
     * @throws \Exception
     */
    public function destroy($data)
    {
        $id = $data['id']??0;
        if ($id<=0) {
            throw new \Exception(ErrorCode::getMessage(ErrorCode::DATA_NOT_EXIST));
        }
        $role = \App\Model\Role::query()->find($id);
        if (! $role) {
            throw new \Exception(ErrorCode::getMessage(ErrorCode::DATA_NOT_EXIST));
        }
        $administrators = $role->administrators()->get();
        if ($administrators->count() > 0) {
            throw new \Exception('此角色拥有管理员，请先移除管理员后再操作!');
        }
        $rt = $role->delete();
        if (!$rt){
            throw new \Exception(ErrorCode::getMessage(ErrorCode::UPDATE_ERROR));
        }
        return [];
    }
}